package com.example.administrator.myapplication;

import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {
    private MyReceiver receiver;
    private LocalReceiver localReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        localReceiver = new LocalReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("LOCAL_BROADCAST");
        LocalBroadcastManager manager = LocalBroadcastManager.getInstance(MainActivity.this);
        manager.registerReceiver(localReceiver,intentFilter);

        //本地广播
        findViewById(R.id.btn_local).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction("LOCAL_BROADCAST");

                //设计模型——单例模式
                LocalBroadcastManager manager = LocalBroadcastManager.getInstance(MainActivity.this);
                manager.sendBroadcast(intent);

                //sendOrderedBroadcast(intent,null);
            }
        });

        //动态注册接收者
        receiver = new MyReceiver();
        //intent过滤器
        IntentFilter filter = new IntentFilter();
        filter.addAction("WEATHER_INFO");
        filter.addAction("TRAFFIC_INFO");
        registerReceiver(receiver,filter);

        //普通广播
        findViewById(R.id.btn_weather).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction("WEATHER_INFO");
                intent.putExtra("WEATHER","晴朗");
                intent.putExtra("TEMPERATURE",35);
                sendBroadcast(intent);
            }
        });

        findViewById(R.id.btn_traffic).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction("TRAFFIC_INFO");
                intent.putExtra("TRAFFIC","堵塞");
                intent.putExtra("TIME",5);
                sendBroadcast(intent);
            }
        });
    }

    @Override
    protected void onDestroy() {
        //注册与销毁最好写在onResume()和onPause()
        //onDestroy(),若直接按home键，应用未销毁，其他应用可接收到，不安全
        //销毁广播
        unregisterReceiver(receiver);
        super.onDestroy();
    }
}
